<template>
  <div class="project-org-page">
    <el-container style="height:100%">
      <el-aside width="20%" class="org-aside">
        <avue-tree :option="orgInfo.orgTreeOption"
                    :data="orgInfo.orgTreeData"
                    @save="addOrg"
                    @update="updateOrg"
                    @del="deleteOrg"
                    @node-click="getAllStaff"
                    v-model="orgInfo.orgForm">
        </avue-tree>
      </el-aside>
      <el-main>
        <avue-crud ref="crud" 
                    :data="orgInfo.orgStaffData" 
                    :option="orgInfo.orgStaffOption"
                    :page.sync="orgInfo.orgPage"
                    @row-update="updateOrgStaff"
                    @current-change="orgStaffCurrentChange"
                    @size-change="orgStaffSizeChange">
          <template slot-scope="scope" slot="menuLeft">
            <el-button type="primary"
                      size="small"
                      icon="el-icon-plus"
                      @click.stop="openAddUserDialog">新增人员
            </el-button>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button type="text"
                      size="small"
                      icon="el-icon-user"
                      @click="openRoleDialog(scope.row)">设置角色
            </el-button>
          </template>
        </avue-crud>
      </el-main>
    </el-container>

    <!-- 
      批量添加用户对话框
    -->
    <el-dialog title="批量添加用户" :fullscreen='true' :close-on-click-modal='false' :visible.sync="orgInfo.addUserDialog">
      <general-staff-info-dialog 
        ref="childDialog"
        :hasSelectIds="orgInfo.oldUserListValue"
        @handleBatchAdd="handleBatchAdd"
        @getDialogStaffList="getDialogStaffList">
      </general-staff-info-dialog>
    </el-dialog>

    <!-- 
      添加角色对话框
    -->
    <el-dialog title="选择用户角色" width="800px"  :close-on-click-modal='false' @close="roleDialogClosed" :visible.sync="orgInfo.roleDialog">
        <el-transfer v-model="orgInfo.roleValue" 
          filterable
          :titles="['可选角色', '已选角色']"
          :button-texts="['移除', '添加 ']"
          :data="orgInfo.roleData">
        </el-transfer>
        <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handleAddUserRole($event)" >确定</el-button>
        <el-button size="small" @click="roleDialogClosed">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {mapGetters} from 'vuex';
import {saveOrUpdateSysUserRoleRelationList} from '@/api/system/sysUserRoleRelationApi';
import {querySysRoleListPage,querySysRoleListByUserId} from '@/api/system/sysRoleApi';
import {queryGeneralOrgStaffRelationListPage,saveOrUpdateGeneralOrgStaffRelationList,updateGeneralOrgStaffRelation} from '@/api/general/staff/generalOrgStaffRelationApi';
import {queryGeneralOrgTree,queryGeneralOrgInfoListPage,saveGeneralOrgInfo,updateGeneralOrgInfo,deleteGeneralOrgInfo,queryGeneralOrgInfo} from '@/api/general/staff/generalOrgInfoApi';
import GeneralStaffInfoDialog from '@/views/general/staff/generalStaffInfoDialog.vue'
export default {
  name: 'projectOrgPage',
  props: {
    projectInfo: {
      type: Object
    }
  },
  components: {
    GeneralStaffInfoDialog
  },
  data () {
    return {
      // 组织架构信息
      orgInfo: {
        // 请求参数区
        orgPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        // 组织架构form
        orgFormOption: {
          // emptyBtn: false,
          column:[
            {
              label: '组织全名',
              prop: 'orgFullName', 
              type: 'input', 
              multiple: false,
              span: 12,
              rules: [{
                required:  true,
                message: '请输入内容',
                trigger: 'blur'
              }]
            },
            {
              label: '组织编号',
              prop: 'orgNo', 
              type: 'input', 
              multiple: false,
              span: 12,
              rules: [{
                required:  true,
                message: '请输入内容',
                trigger: 'blur'
              }]
            },
            {
              label: '上级组织',
              prop: 'parentOrgNo', 
              multiple: false,
              span: 12,
              rules: [{
                required:  true,
                message: '请输入内容',
                trigger: 'blur'
              }],
              props: {
                label: 'orgName',
                value: 'orgNo'
              },
              type:'tree',
              dicData: [],
            }, 
            {
              label: '负责人',
              prop: 'respsbUserName', 
              type: 'select',
              props: {
                label: 'userName',
                value: 'realName',
              },
              dicData:[],
              remote: true,
              dicMethod:'get',
              value: '',
              dicUrl: '/platform/sysUserInfo/querySysUserInfoListPage?optFlag=org&remote=yes&columnValue={{key}}&columnName=realName&tenantId='+localStorage.getItem('tenantId'),
              rules: [{
                required:  false,
                message: '请输入内容',
                trigger: 'blur'
              }],
            },
            {
              label: '排序序号',
              prop: 'orderSeq', 
              type: 'number', 
              multiple: false,
              span: 12,
              value: '1',
              rules: [{
                required:  false,
                message: '请输入内容',
                trigger: 'blur'
              }]
            },
            {
              label: '备注',
              prop: 'remark', 
              type: 'textarea', 
              multiple: false,
              span: 24,
              rules: [{
                required:  false,
                message: '请输入内容',
                trigger: 'blur'
              }]
            },
            // 公共字段
            {
              prop: 'validFlag',
              display: false
            },
            {
              prop: 'dataSign',
              display: false
            },
            {
              prop: 'createUserName',
              display: false
            },
            {
              prop: 'createRealName',
              display: false
            },
            {
              prop: 'createDatetime',
              display: false
            },
            {
              prop: 'updateUserName',
              display: false
            },
            {
              prop: 'updateRealName',
              display: false
            },
            {
              prop: 'updateDatetime',
              display: false
            }
          ],
        },
        // 组织架构option
        orgTreeOption:{
          addBtn: true,
          editBtn: true,
          delBtn: true,
          defaultExpandAll:false,
          dialogClickModal: false,
          formOption: {},
          props: {
            labelText:'机构名称',
            label: 'orgName',
            value: 'orgName'
          }
        },
        // 组织架构表单
        orgForm: {},
        // 组织架构数据
        orgTreeData: [],
  
        // 选中的组织架构信息
        currentOrgInfo: {},
  
        // 组织架构新增人员
        addUserDialog: false,
  
        // 组织架构人员信息
        oldUserListValue: [],
        staffList: [],
        orgStaffData: [],
        orgStaffOption: {
          border: true,
          align:'center',
          columnBtn: false,
          filterBtn: false,
          editBtn: true,
          editBtnText: '移动',
          delBtn: false,
          addBtn: false,
          column: [
            {
              label: '机构名称',
              prop: 'belongOrgName', 
              type: 'tree', 
              search: false,
              searchMmultiple: false,
              searchLabelWidth: 100,
              multiple: false,
              span: 12,
              sortable: false,
              hide: false,
              overHidden: true,
              display: false,
              width: 200,
              rules: [{
                required:  true,
                message: '请输入内容',
                trigger: 'blur'
              }],
              dicData:[]
            },
            {
              label: '角色',
              prop: 'roleName', 
              type: 'input', 
              search: false,
              searchMmultiple: false,
              searchLabelWidth: 100,
              multiple: false,
              span: 12,
              sortable: false,
              hide: false,
              overHidden: true,
              display: false,
              rules: [{
                required:  true,
                message: '请输入内容',
                trigger: 'blur'
              }],
              dicData:[]
            },
            {
              label: '用户名',
              prop: 'staffName', 
              type: 'input', 
              search: false,
              searchMmultiple: false,
              searchLabelWidth: 100,
              multiple: false,
              span: 12,
              sortable: false,
              hide: false,
              width: 120,
              overHidden: true,
              display: false,
              rules: [{
                required:  true,
                message: '请输入内容',
                trigger: 'blur'
              }],
              dicData:[]
            },
            {
              label: '姓名',
              prop: 'realName', 
              type: 'input', 
              search: false,
              searchMmultiple: false,
              searchLabelWidth: 100,
              multiple: false,
              span: 12,
              sortable: false,
              hide: false,
              overHidden: true,
              disabled: true,
              width: 150,
              rules: [{
                required:  true,
                message: '请输入内容',
                trigger: 'blur'
              }],
              dicData:[]
            },
            {
              label: '所属机构',
              prop: 'belongOrgNo', 
              type: 'tree', 
              search: false,
              searchMmultiple: false,
              searchLabelWidth: 100,
              multiple: false,
              span: 12,
              sortable: false,
              hide: true,
              overHidden: true,
              display: true,
              width: 200,
              rules: [{
                required:  true,
                message: '请输入内容',
                trigger: 'blur'
              }],
              props: {
                label: 'orgName',
                value: 'orgNo'
              },
              dicData:[]
            },
            {
              label: '用户标识',
              prop: 'userId', 
              type: 'input', 
              search: false,
              searchMmultiple: false,
              searchLabelWidth: 100,
              multiple: false,
              span: 12,
              sortable: false,
              hide: false,
              overHidden: true,
              slot: true,
              formslot: true,
              display: false,
              rules: [{
                required:  true,
                message: '请输入内容',
                trigger: 'blur'
              }],
              dicData:[]
            }
          ]
        },

        // 组织架构选择的人员行
        currentRow: {},
        // 设置角色对话框
        roleDialog: false,
        roleData: [],
        roleValue: [],
        oldRoleValue: [],
      },
    }
  },
  watch: {
    // orgConfig: {
    //   handler (val) {
    //     this.orgInfo = this.deepClone(this.orgConfig);
    //   },
    //   deep: true
    // },
  },
  computed: {
    ...mapGetters(['website','userInfo','orgTree','permission','genOrgTree'])
  },
  created() { 
    
  },
  mounted(){
    this.loadOrgTreeData();
  },
  methods:{
    /**
     * 新增组织架构
     */
    addOrg(data, parent, done, loading){
      let singleBody = {
        orgName: this.orgInfo.orgForm.orgName,
        orgFullName: this.orgInfo.orgForm.orgFullName,
        orgNo: this.orgInfo.orgForm.orgNo,
        parentOrgNo: data.orgNo,
        orgType: '2',
        belongProjectNo: data.belongProjectNo
      }
      let reqParams =  {
        singleBody: singleBody
      }
      let commonData = reqCommonMsg(reqParams)
      saveGeneralOrgInfo(commonData).then(() => {
        this.loadOrgTreeData();
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        //this.$console.log(error);
        loading();
      });    
    },
    /**
     * 修改组织架构
     */
    updateOrg(data, parent, done, loading){
      if(parent.orgNo == parent.parentOrgNo) {
        this.$message({
          customClass:'zZindex',
          type: 'error',
          message: '上级组织不能是自己!'
        });
        done();
        this.loadOrgTreeData();
        return false;
      }

      let singleBody = parent;
      let reqParams = {
        singleBody: singleBody
      }
      let commonData = reqCommonMsg(reqParams)
      updateGeneralOrgInfo(commonData).then(() => {
        done();
        this.loadOrgTreeData();
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });  
    },
    /**
     * 删除组织架构
     */
    deleteOrg(data,done){
      this.$confirm('此操作将永久删除该机构, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let reqParams = {
          singleBody: data
        };
        let commonData = reqCommonMsg(reqParams);
        return deleteGeneralOrgInfo(commonData);
        done();
      }).then(() => {
        this.loadOrgTreeData();
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }).catch(() => {});
    },
    /**
     * 保存用户列表
     */
    handleBatchAdd(userListValue){
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading',
      });
      // 前后角色对比，给新增和删除的打上标识
      let resultList = [];
      // 原列表不存在的表示新增的元素
      let inOldValue = false;
      let inNewValue = false;

      // 判断是否有新增数据
      userListValue.forEach(element => {
        inOldValue = false;
        for(var i = 0 ; i < this.orgInfo.oldUserListValue.length; i++){
          if (element.id == this.orgInfo.oldUserListValue[i]) {
            inOldValue = true;
            i = this.orgInfo.oldUserListValue.size + 1;
          }
        }
        //若没找到表示新增元素
        if(!inOldValue){
          resultList.push({
            belongOrgNo: this.orgInfo.currentOrgInfo.orgNo,
            belongOrgName: this.orgInfo.currentOrgInfo.orgName,
            staffId: element.id,
            staffName: element.staffId,
            realName: element.staffName,
            validFlag: '1'
          })
        }
      });

      // 判断是否有删除数据
      this.orgInfo.oldUserListValue.forEach(id => {
        inNewValue = false;
        for(var i = 0 ; i < userListValue.length; i++){
          if (id == userListValue[i].id) {
            inNewValue = true;
            i = userListValue.size + 1;
          }
        }
        //若没找到表示删除元素
        if(!inNewValue){
          for(var i = 0 ; i < this.orgInfo.staffList.length; i++){
            if(id == this.orgInfo.staffList[i].id){
              resultList.push({
                belongOrgNo: this.orgInfo.currentOrgInfo.orgNo,
                belongOrgName: this.orgInfo.currentOrgInfo.orgName,
                staffId: this.orgInfo.staffList[i].id,
                staffName: this.orgInfo.staffList[i].staffId,
                realName: this.orgInfo.staffList[i].staffName,
                validFlag: '0'
              })
              i = this.orgInfo.staffList.length + 1;
            }
          }
        }
      });

      if(resultList.length > 0){
        let reqParams =  {
          transCode: '0001',
          listBody: resultList
        }
        let commonData = reqCommonMsg(reqParams)
        saveOrUpdateGeneralOrgStaffRelationList(commonData).then(() => {
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '添加成功!'
          });
          this.getAllStaff(this.orgInfo.currentOrgInfo);
          userListValue = null;
          this.orgInfo.addUserDialog = false;
          loading.close();
        }, error => {
          //this.$console.log(error);
          loading.close();
        });
      }else{
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '用户未发生变化!'
        });
        loading.close();
      }
    },
    /**
     * 获取添加用户弹窗查询出的用户列表信息
     */
    getDialogStaffList(staffList){
      this.orgInfo.staffList = staffList;
    },
    /**
     * 组织架构人员翻页查询
     */
    orgStaffCurrentChange(currentPage) {
      this.orgInfo.orgPage.currentPage = currentPage;
    },
    /**
     * 组织架构人员更改每页条数
     */
    orgStaffSizeChange(pageSize) {
      this.orgInfo.orgPage.pageSize = pageSize;
    },
    /**
     * 打开添加用户对话框
     */
    openAddUserDialog(){
      if(this.orgInfo.currentOrgInfo.orgNo){
        this.orgInfo.addUserDialog =  true;
        this.$nextTick(() => {
          this.$refs.childDialog.onLoad({
            pageSize: 10,
            currentPage: 1,
            total: 0
          });
        })
      }else{
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '请先选择一个左边的组织架构再添加！！!'
        });
      }
    },
    /**
     * 打开角色对话框
     */
    async openRoleDialog(row){
      if(!row.userId){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '当前人员还未注册账号！！!'
        });
        return false;
      }
      this.orgInfo.currentRow = row;
      let singleBody = {};
      //获取所有角色列表
      let reqParams =  {
        singleBody: singleBody,
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      let commonData = reqCommonMsg(reqParams)
      await querySysRoleListPage(commonData).then(res => {
        res.data.body.listBody.forEach(element => {
          this.orgInfo.roleData.push({
            key: element.id,
            label: '['+element.roleGroupName+']'+element.roleNickName,
            disabled: (element.status == '0') ? true: false
          });
        });
      }, error => {
        
      });

      //获取当前用户的角色
      reqParams =  {
        singleBody: {
          userId: row.userId
        },
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      commonData = reqCommonMsg(reqParams)
      await querySysRoleListByUserId(commonData).then(res => {
        res.data.body.listBody.forEach(element => {
          this.orgInfo.roleValue.push(element.id);
        });
        this.orgInfo.oldRoleValue = this.deepClone(this.orgInfo.roleValue)
        this.orgInfo.roleDialog = true;
      }, error => {
        
      });
    },
    /**
     * 保存角色
     */
    handleAddUserRole(){
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading',
      });
      // 前后角色对比，给新增和删除的打上标识
      let resultList = [];
      // 原列表不存在的表示新增的元素
      let inOldValue = false;
      let inNewValue = false;
      this.orgInfo.roleValue.forEach(element => {
        inOldValue = false;
        for(var i = 0 ; i < this.orgInfo.oldRoleValue.length; i++){
          if (element == this.orgInfo.oldRoleValue[i]) {
            inOldValue = true;
            i = this.orgInfo.oldRoleValue.size + 1;
          }
        }
        //若没找到表示新增元素
        if(!inOldValue){
          resultList.push({
            userId: this.orgInfo.currentRow.userId,
            roleId: element,
            validFlag: '1'
          })
        }
      });

      //新列表中不存在 表示 删除元素
      this.orgInfo.oldRoleValue.forEach(element => {
        inNewValue = false;
        for(var i = 0 ; i < this.orgInfo.roleValue.length; i++){
          if (element == this.orgInfo.roleValue[i]) {
            inNewValue = true;
            i = this.orgInfo.roleValue.size + 1;
          }
        }
        //若没找到表示删除元素
        if(!inNewValue){
          resultList.push({
            userId: this.orgInfo.currentRow.userId,
            roleId: element,
            validFlag: '0'
          })
        }
      });

      if(resultList.length > 0){
        let reqParams =  {
          transCode: '0001',
          listBody: resultList
        }
        let commonData = reqCommonMsg(reqParams)
        saveOrUpdateSysUserRoleRelationList(commonData).then(() => {
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '保存成功!'
          });
          this.orgInfo.roleDialog = false;
          loading.close();
        }, error => {
          //this.$console.log(error);
          loading.close();
        });
      }
      else{
        loading.close();
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '角色未发生变化!'
        });
      }
    },
    /**
     * 角色对话框结束时回调
     */
    roleDialogClosed(done){
      this.orgInfo.roleDialog = false;
      this.orgInfo.roleData = [];
      this.orgInfo.roleValue = [];
    },
    /**
     * 获取组织下的所有人员
     */
    getAllStaff(data){
      this.orgInfo.currentOrgInfo = data
      let singleBody = {
        belongOrgNo: data.orgNo
      }
      let reqParams =  {
        singleBody: singleBody,
        currentPage: this.orgInfo.orgPage.currentPage, 
        pageSize: this.orgInfo.orgPage.pageSize
      }
      let commonData = reqCommonMsg(reqParams)
      queryGeneralOrgStaffRelationListPage(commonData).then(res => {
        this.orgInfo.orgStaffData = res.data.body.listBody;
        this.orgInfo.oldUserListValue = [];
        this.orgInfo.orgStaffData.forEach(element => {
          if(element.belongOrgNo === data.orgNo){
            this.orgInfo.oldUserListValue.push(element.staffId)
          }
        });
      }, error => {
      });
    },
    /**
     * 组件调用加载组织下的所有人员
     */
    invokeGetAllStaff(){
      let data = this.orgInfo.orgTreeData[0];
      this.getAllStaff(data);
    },
    /**
     * 加载项目组织架构
     */
    loadOrgTreeData(node, resolve){
      // 加载树形组织列表
      let singleBody = {
        orgNo: this.projectInfo.id
      }
      let reqParams =  {
        singleBody: singleBody
      }
      let commonData = reqCommonMsg(reqParams)
      queryGeneralOrgTree(commonData).then(res => {
        this.orgInfo.orgTreeData = res.data.body.listBody;
        const column = this.findObject(this.orgInfo.orgFormOption.column, 'parentOrgNo');
        column.dicData = [];
        column.dicData = this.deepClone(res.data.body.listBody);
        this.orgInfo.orgTreeOption.formOption = this.deepClone(this.orgInfo.orgFormOption);

        const orgStaffColumn = this.findObject(this.orgInfo.orgStaffOption.column, 'belongOrgNo');
        orgStaffColumn.dicData = [];
        orgStaffColumn.dicData = this.deepClone(res.data.body.listBody);
      }, error => {
      });
    },
    /**
     * 更新人员所属组织架构
     */
    async updateOrgStaff(row, index, done, loading){
      // 所属机构名称
      let belongOrgName = '';

      let singleBody = {
        belongProjectNo: this.projectInfo.id,
        orgNo: row.belongOrgNo
      }
      let reqParams = {
        singleBody: singleBody,
        currentPage: 1, 
        pageSize: 99999
      };
      let commonData = reqCommonMsg(reqParams)
      await queryGeneralOrgInfoListPage(commonData).then(res => {
        const data = res.data.body.listBody;
        if(data){
          belongOrgName = data[0].orgName;
        }else{
          this.$message({
            customClass:'zZindex',
            type: 'error',
            message: '所属机构不存在!'
          });
          return;
        }
      }, error => {
        this.loading = false; 
      });

      singleBody = row;
      singleBody.belongOrgName = belongOrgName;
      singleBody.moveStaffOrgFlag = '1';
      reqParams = {
        singleBody: singleBody,
      }
      commonData = reqCommonMsg(reqParams)
      updateGeneralOrgStaffRelation(commonData).then(() => {
        done();
        this.singleBody={}
        this.getAllStaff(this.orgInfo.currentOrgInfo);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });
    },
  }
}
</script>
<style lang="scss">
  .project-org-page{
    height: 100%;
  }
</style>